<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of GlobalFunction
 *
 * @author hasee
 */
class GlobalFunction {

    private static $instance = null;

    /**
     * 获取该对象的单例
     * @return type
     */
    public static function getInstance() {
        if (null == self::$instance) {
            self::$instance = new GlobalFunction();
        }
        return self::$instance;
    }

    //自己添加公共方法
    //FIXME

    /**
     * 获取当前时间  
     * @param type $formate 时间格式 
     * @return type
     */
    public function getNow($formate = "Y-m-d H:i:s") {
        return date($formate);
    }

    /**
     * 返回json数据给前台
     * @param type $success 状态
     * * @param type $data 数据
     * @param type $code  代码
     * @param type $msg 消息
     */
    public static function returnJSON($success = false, $data = [], $code = 0, $msg = "") {
        $return = array(
            "success" => $success,
            'code' => $code,
            'data' => $data,
            'msg' => $msg
        );
        //设置类型
        header("content-type:application/json");
        echo json_encode($return);
        die;
    }

    /**
     *  导出excel并下载
     * @param type $expTitle  要导出的文件名称   后面会自动添加日期
     * @param type $expCellName 要导出的标题  一维数组
     * @param type $expTableData 要导出的数据 二维数组
     * 
     */
    public static function exportExcel($expTitle, $expCellName, $expTableData, $cellStyle = array()) {
        $xlsTitle = iconv('utf-8', 'gb2312', $expTitle); //文件名称
        $fileName = $expTitle . date('_YmdHis'); //or $xlsTitle 文件名称可根据自己情况设定
        $cellNum = count($expCellName);
        $dataNum = count($expTableData);
        require_once LIBRARY_PATH . 'PHPExcel.php';
        $objPHPExcel = new PHPExcel();

        $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
//  $objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $cellName[$cellNum - 1] . '1'); //合并单元格
        for ($i = 0; $i < $cellNum; $i++) {
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i] . '1', $expCellName[$i]);
        }
        // Miscellaneous glyphs, UTF-8
        $activeSheet = $objPHPExcel->getActiveSheet(0);
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {

                //
                if (array_key_exists($expCellName[$j], $cellStyle)) {
                    $activeSheet->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j]],$cellStyle[$expCellName[$j]]);
                } else {
                    $activeSheet->setCellValue($cellName[$j] . ($i + 2), $expTableData[$i][$expCellName[$j]]);
                }
            }
        }
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $xlsTitle . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls"); //attachment新窗口打印inline本窗口打印
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }

    /**
     * 显示前台错误消息  然后结束脚本
     * @param type $msg
     */
    public static function showErrorMsg($msg, $url = "") {
        if ($url !== "") {
            echo "<script>alert('$msg');window.location.href='{$url}';</script>";
        } else {
            echo "<script>alert('$msg');</script>";
        }
        die;
    }

    /**
     * 随机字符
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string
     */
    public static function getRandom($length = 6, $type = 'string', $convert = 0) {
        $config = array(
            'number' => '1234567890',
            'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if (!isset($config[$type])) {
            $type = 'string';
        }
        $string = $config[$type];

        $code = '';
        $strlen = strlen($string) - 1;
        for ($i = 0; $i < $length; $i++) {
            $code .= $string{mt_rand(0, $strlen)};
        }
        if (!empty($convert)) {
            $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

    /**
     * 
     * @param type $savePath 保存的路径
     * @param type $saveName 保存的文件名称
     * @param type $fileObj $_FILED[xxx]
     * @param type $msg
     * @return boolean
     */
    function uploadFile($savePath, $saveName, $fileObj, &$msg = "") {

        if (!file_exists($savePath)) {
            if (!$this->makeDir($savePath)) {
                $msg = "文件夹创建失败";
                return false;
            }
        }

        /* 是否上传成功 */
        if (!move_uploaded_file($fileObj ['tmp_name'], $savePath . $saveName)) {
            $msg = "文件移动失败 ";
            return false;
        }
        return $savePath . $saveName;
    }

    /*     * *
     * 创建目录
     */

    function makeDir($path) {
//    $dirs = explode(DS, $path);
//    if (is_array($dirs)) {
//        foreach ($dirs as $value) {
//            
//        }
//    } else {
//        mkdir($path, 777,true);
//    }
        return mkdir($path, 0777, true);
    }

    /**
     * 获取该目录下的所有文件
     * @param type $path
     */
    public static function loadAllFiles($path, $ext = null) {
        
    }

}
